package com.mybatis.config;

import com.mybatis.entity.Configuration;
import com.mybatis.entity.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 创建人: yyn
 * 创建时间:2021/7/8 22:47
 */
public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws Exception {
        Document read = new SAXReader().read(inputStream);
        Element rootElement = read.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        parseSelect(rootElement.selectNodes("//select"), namespace);

        parseInsert(rootElement.selectNodes("//insert"), namespace);

        parseUpdate(rootElement.selectNodes("//update"), namespace);

        parseDelete(rootElement.selectNodes("//delete"), namespace);


    }

    private void parseDelete(List<Element> elements, String namespace) {
        put(elements, namespace, "delete");
    }
    private void parseUpdate(List<Element> elements, String namespace) {
        put(elements, namespace, "update");
    }
    private void parseInsert(List<Element> elements, String namespace) {
        put(elements, namespace, "insert");
    }

    public void parseSelect(List<Element> elements, String namespace) {
        put(elements, namespace, "select");
    }

    public void put(List<Element> elements, String namespace, String type) {
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setType(type);
            String key = namespace + "." + id;
            configuration.getMappedStatements().put(key, mappedStatement);

        }

    }
}
